from itsdangerous import TimedJSONWebSignatureSerializer
from flask import current_app
from comment.models.user import User
from comment.utils.const import SECRET_KEY, JWT_EXPRISON_TIMEOUT


def generate(uid):
    """
    生成密钥
    :param uid:
    :return:
    """
    # 两个参数：参数一：密钥  参数二：过期时间
    s = TimedJSONWebSignatureSerializer(SECRET_KEY, JWT_EXPRISON_TIMEOUT)
    # 返回的是一个字节数据，需要转为字符数据
    return s.dumps({'id': uid}).decode()


def check_uid(token_str):
    """
    验证token，并且返回用户当前的id
    :param token_str:
    :return:
    """
    s = TimedJSONWebSignatureSerializer(SECRET_KEY, JWT_EXPRISON_TIMEOUT)
    try:
        data = s.loads(token_str)
    except Exception as e:
        current_app.logger.info(e)
        return {'message': 'token验证失败'}
    # 如果token验证成功，还需要检查用户的状态是否正常
    # 获取当前用户
    user = User.query.filter(User.id == data['id']).first()
    if user and user.status != 0:
        return {'message': '数据库中的状态用户过期'}
    return {'id': user.id}
